package faa;

import java.util.*;
import faa.objects.*;
import faa.users.*;
import agent.*;

enum RiskUpdate { NEW, STALE }
enum ActionUpdate { NEW, STALE }

public class RiskManager extends Agent {
	
	private LinkedList<Risk> RiskList = new LinkedList<Risk>();
	private LinkedList<Action> ActionList = new LinkedList<Action>();
	private RiskUpdate riskUpdate;
	private ActionUpdate actionUpdate;
	private User user;
	private RealWorld realWorld;
	private LogManager logManager;
	Random generator = new Random(); //only used for skeleton submission
	
	//Constructor
	public RiskManager() {
		super();
	}
	
	//Messages
	
	public void msgActionDone( Action action ) {
		ActionList.add(action);
		actionUpdate = ActionUpdate.NEW;
		stateChanged();
	}
	
	public void msgRisks( LinkedList<Risk> RiskList ) {
		if (RiskList.isEmpty()) {
			this.RiskList = RiskList;
			riskUpdate = RiskUpdate.NEW;
			stateChanged();
		}
		else {
			//this.RiskList.addAll( LinkedList<Risk> RiskList ); //this doesn't seem to work--is there another way to do this?
			for (int i = RiskList.size()-1; i >= 0; i--) { // I think this is the easiest workaround, but I might be off with the iterator --Ryan
				this.RiskList.add(RiskList.get(i));
			}
			riskUpdate = RiskUpdate.NEW;
			stateChanged();
		}
	}
	
	/* Scheduler */
	protected boolean pickAndExecuteAnAction() {
	
		if ( actionUpdate == ActionUpdate.NEW ) {
			realWorld.msgSensorData(ActionList);
			actionUpdate = ActionUpdate.STALE;
			logActions();
		}
		
		if ( riskUpdate == RiskUpdate.NEW ) {
			sortRisks();
			user.msgDoThese(RiskList);
			riskUpdate = RiskUpdate.STALE;
		}
	}
	
	/*Sort Risk Function
	*No real functionality right now, but will be updated
	*to introduce real functionality to sort risks by severity.
	*/
	private void sortRisks() {
		Integer random;
		for ( int i = 0; i < RiskList.size(); i++ ) {
			random = generator.nextInt();
				if ( i == 1 ) //try to create a small amount of high risks
					RiskList.get(i).setRiskPriorityHigh();
				else if ( 1 < i && i < 5) //allow for more medium risks
					RiskList.get(i).setRiskPriorityMedium();	
				else //make a lot of low priority risks
					RiskList.get(i).setRiskPriorityLow();
		}
	}
	private void logActions() {
		for ( int i = 0; i < ActionList.size(); i++ ) {
			logManager.msgLogThis(ActionList.get(i).getActionType());
			ActionList.clear();
		}
	}
}
